package bjx.com.kehu.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import bjx.com.kehu.R;
import bjx.com.kehu.contants.Constants;
import bjx.com.kehu.model.CarTypeModel;
import bjx.com.kehu.utils.GsonUtil;
import bjx.com.kehu.utils.MD5;
import bjx.com.kehu.utils.SPUtils;
import bjx.com.kehu.utils.Util;
import com.yongchun.library.view.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jqc on 2017/10/25.
 */

public class EnrollActivity extends BaseActivity {

    ImageView mIVBack;
    TextView mTVTitle;

    EditText mETName; // 名称
    EditText mETTel; // 手机号
    CheckBox mCBMan;
    CheckBox mCBWoMan;
    Spinner mSpnCarType;
    TextView mTVIdFrontstr;
    TextView mTVIdBackstr;
    TextView mTVDrivingIdFrontstr;
    TextView mTVDrivingIdBackstr;
    TextView mTVIdFront; // 身份证正面
    ImageView mIVIdFront;
    RelativeLayout mLLIdFront;
    TextView mTVIdBack;  // 身份证反面
    ImageView mIVIdBack;
    RelativeLayout mLLIdBack;
    TextView mTVDrivingIdFront; // 行驶证正面
    ImageView mIVDrivingIdFront;
    RelativeLayout mLLDrivingIdFront;
    TextView mTVDrivingIdBack; // 行驶证反面
    ImageView mIVDrivingIdBack;
    RelativeLayout mLLDrivingIdBack;
    TextView mTVJSZ; // 驾驶证
    ImageView mIVJSZ;
    RelativeLayout mLLJSZ;
    CheckBox mCBLocala;
    CheckBox mCBLocalb;
    CheckBox mCBLic;
    TextView mTVLic;
    TextView mTVSub;

    String cartype = "1";
    String idFrontUrl = "";
    String idBackUrl = "";
    String drivingIdFrontUrl = "";
    String drivingIdBackUrl = "";
    String jszUrl = "";

    ArrayAdapter<CarTypeModel> adapter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_enroll);
        mIVBack = getViewById(R.id.back);
        mTVTitle = getViewById(R.id.title);
        mTVTitle.setText("司机报名");

        mETName = getViewById(R.id.enroll_et_name);
        mETTel = getViewById(R.id.enroll_et_tel);
        mCBMan = getViewById(R.id.enroll_cb_man);
        mCBWoMan = getViewById(R.id.enroll_cb_woman);
        mSpnCarType = getViewById(R.id.enroll_spn_cartype);
        mTVIdFrontstr = getViewById(R.id.enroll_tv_idfrontstr);
        mTVIdBackstr = getViewById(R.id.enroll_tv_idbackstr);
        mTVDrivingIdFrontstr = getViewById(R.id.enroll_tv_drivingidfrontstr);
        mTVDrivingIdBackstr = getViewById(R.id.enroll_tv_drivingidbackstr);
        mTVIdFront = getViewById(R.id.enroll_tv_idfront);
        mIVIdFront = getViewById(R.id.enroll_iv_idfront);
        mLLIdFront = getViewById(R.id.enroll_ll_idfront);
        mTVIdBack = getViewById(R.id.enroll_tv_idback);
        mIVIdBack = getViewById(R.id.enroll_iv_idback);
        mLLIdBack = getViewById(R.id.enroll_ll_idback);
        mTVDrivingIdFront = getViewById(R.id.enroll_tv_drivingidfront);
        mIVDrivingIdFront = getViewById(R.id.enroll_iv_drivingidfront);
        mLLDrivingIdFront = getViewById(R.id.enroll_ll_drivingidfront);
        mTVDrivingIdBack = getViewById(R.id.enroll_tv_drivingidback);
        mIVDrivingIdBack = getViewById(R.id.enroll_iv_drivingidback);
        mLLDrivingIdBack = getViewById(R.id.enroll_ll_drivingidback);
        mTVJSZ = getViewById(R.id.enroll_tv_jsz);
        mIVJSZ = getViewById(R.id.enroll_iv_jsz);
        mLLJSZ = getViewById(R.id.enroll_ll_jsz);
        mCBLocala = getViewById(R.id.enroll_cb_locala);
        mCBLocalb = getViewById(R.id.enroll_cb_localb);
        mCBLic = getViewById(R.id.enroll_cb_lic);
        mTVLic = getViewById(R.id.enroll_tv_lic);
        mTVSub = getViewById(R.id.enroll_tv_sub);
    }

    @Override
    protected void setListener() {
        mIVBack.setOnClickListener(this);
        mCBMan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCBWoMan.setChecked(false);
                }
            }
        });
        mCBWoMan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCBMan.setChecked(false);
                }
            }
        });
        mSpnCarType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cartype = adapter.getItem(position).getId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mTVIdFront.setOnClickListener(this);
        mLLIdFront.setOnClickListener(this);
        mTVIdBack.setOnClickListener(this);
        mLLIdBack.setOnClickListener(this);
        mTVDrivingIdFront.setOnClickListener(this);
        mLLDrivingIdFront.setOnClickListener(this);
        mTVDrivingIdBack.setOnClickListener(this);
        mLLDrivingIdBack.setOnClickListener(this);
        mTVJSZ.setOnClickListener(this);
        mLLJSZ.setOnClickListener(this);
        mCBLocala.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCBLocalb.setChecked(false);
                }
            }
        });
        mCBLocalb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCBLocala.setChecked(false);
                }
            }
        });
        mTVLic.setOnClickListener(this);
        mTVSub.setOnClickListener(this);
    }

    List<CarTypeModel> list = new ArrayList<>();
    @Override
    protected void processLogic(Bundle savedInstanceState) {
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpnCarType.setAdapter(adapter);

        mEngine.loadCarType().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");

                    if (status == 200) {
                        List<CarTypeModel> mList = new ArrayList<>();
                        TreeMap<String, Object> map = GsonUtil.jsonToTreeMap(jo.getString("result"));
                        Set<String> keySet = GsonUtil.jsonToTreeMap(jo.getString("result")).keySet();
                        Iterator<String> iter = keySet.iterator();
                        while (iter.hasNext()) {
                            String key = iter.next();
                            mList.add(new CarTypeModel(key, (String) map.get(key)));
                        }
                        adapter.addAll(mList);
                    } else if (status == 100) {
                        showToast("请求失败");
                    } else {
                        showToast("请求异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.enroll_tv_idfront: // 身份证正面
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                            return;
                        }
                    }
                }
                ImageSelectorActivity.start(this, 1, ImageSelectorActivity.MODE_MULTIPLE, true, true, false, 1001);
                break;
            case R.id.enroll_ll_idfront: // 正面图区域

                break;
            case R.id.enroll_tv_idback: // 身份证反面
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                            return;
                        }
                    }
                }
                ImageSelectorActivity.start(this, 1, ImageSelectorActivity.MODE_MULTIPLE, true, true, false, 1002);
                break;
            case R.id.enroll_ll_idback: // 反面图区域
                break;

            case R.id.enroll_tv_drivingidfront: //驾驶证正面
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                            return;
                        }
                    }
                }
                ImageSelectorActivity.start(this, 1, ImageSelectorActivity.MODE_MULTIPLE, true, true, false, 1003);
                break;
            case R.id.enroll_ll_drivingidfront: // 反面图区域
                break;
            case R.id.enroll_tv_drivingidback: // 驾驶证反面
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                            return;
                        }
                    }
                }
                ImageSelectorActivity.start(this, 1, ImageSelectorActivity.MODE_MULTIPLE, true, true, false, 1004);
                break;
            case R.id.enroll_ll_drivingidback: // 反面图区域
                break;

            case R.id.enroll_tv_jsz: // 驾驶证
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                            return;
                        }
                    }
                }
                ImageSelectorActivity.start(this, 1, ImageSelectorActivity.MODE_MULTIPLE, true, true, false, 1005);
                break;
            case R.id.enroll_ll_jsz: // 图区域
                break;

            case R.id.enroll_tv_lic: // 规约
                startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("url", Constants.LIC_URL).putExtra("title", "协议规则"));
                break;
            case R.id.enroll_tv_sub: // 提交
                submit();
                break;
            case R.id.back:
                finish();
                break;
            default:break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1001:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
                    if (images.size() == 1) {
                        String imgPath = images.get(0);
                        postImg(imgPath, 1);
                    }
                }
                break;
            case 1002:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
                    if (images.size() == 1) {
                        String imgPath = images.get(0);
                        postImg(imgPath, 2);
                    }
                }
                break;
            case 1003:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
                    if (images.size() == 1) {
                        String imgPath = images.get(0);
                        postImg(imgPath, 3);
                    }
                }
                break;
            case 1004:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
                    if (images.size() == 1) {
                        String imgPath = images.get(0);
                        postImg(imgPath, 4);
                    }
                }
                break;
            case 1005:
                if (resultCode == RESULT_OK) {
                    ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
                    if (images.size() == 1) {
                        String imgPath = images.get(0);
                        postImg(imgPath, 5);
                    }
                }
                break;
            default:
                break;
        }
    }

    // type 1 身份证正 2 身份证反 3 行驶证正 4 行驶证反 5 驾驶证
    private void postImg(String imgs, final int type) {
        if (imgs == null || imgs.equals("")) {
            return;
        }

        final File file = new File(imgs);
        FileInputStream fis = null;
        long size = 0;
        try {
            fis = new FileInputStream(file);
            size = fis.available();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            showToast("图片不存在");
            return;
        } catch (IOException e) {
            e.printStackTrace();
            showToast("图片读取失败");
            return;
        }
        if (size > 1048576 * 2) {
            showToast("上传的图片不能超过2M");
            return;
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("img", file.getName(), requestBody);
        showLoadingDialog();
        mEngine.upImg(part).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissLoadingDialog();
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    String path = jo.getJSONArray("result").getString(0);
                    if (status == 200) {
                        if (type == 1) {
                            idFrontUrl = path;
                            Glide.with(mApp).load(Uri.fromFile(file)).into(mIVIdFront);
                            mTVIdFrontstr.setVisibility(View.GONE);
                        } else if (type == 2) {
                            idBackUrl = path;
                            Glide.with(mApp).load(Uri.fromFile(file)).into(mIVIdBack);
                            mTVIdBackstr.setVisibility(View.GONE);

                        } else if (type == 3) {
                            drivingIdFrontUrl = path;
                            Glide.with(mApp).load(Uri.fromFile(file)).into(mIVDrivingIdFront);
                            mTVDrivingIdFrontstr.setVisibility(View.GONE);

                        } else if (type == 4) {
                            drivingIdBackUrl = path;
                            Glide.with(mApp).load(Uri.fromFile(file)).into(mIVDrivingIdBack);
                            mTVDrivingIdBackstr.setVisibility(View.GONE);
                        } else if (type == 5) {
                            jszUrl = path;
                            Glide.with(mApp).load(Uri.fromFile(file)).into(mIVJSZ);
                        }
                    } else if (status == 100) {
                        showToast("上传失败");
                    } else {
                        showToast("上传异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissLoadingDialog();
            }
        });
    }

    private void submit() {
        if (!mCBLic.isChecked()) {
            showToast("报名需同意“保驾行”的相关协议");
            return;
        }
        String name = mETName.getText().toString().trim();
        String sex = "";
        String mobile = mETTel.getText().toString().trim();
        String user_id = userModel.getUser_id();
        String sfz_imga = idFrontUrl;
        String sfz_imgb = idBackUrl;
        String jsimg = jszUrl;
        String xsimg_a = drivingIdFrontUrl;
        String xsimg_b = drivingIdBackUrl;
        String cartype = this.cartype;
        String isbendi = "";
        if (mCBMan.isChecked()) {
            sex = "1";
        }
        if (mCBWoMan.isChecked()) {
            sex = "2";
        }
        if (mCBLocala.isChecked()) {
            isbendi = "1";
        }
        if (mCBLocalb.isChecked()) {
            isbendi = "0";
        }
        String fid = (String) SPUtils.get(mApp, "fid", "-1");
        String key = MD5.getMessageDigest((mobile + Constants.BASE_KEY + fid).getBytes());

        if (fid != null && fid.equals("-1")) {
            showToast("当前区域未开放报名");
            return;
        }
        if (name != null && name.equals("")) {
            showToast("姓名不能为空");
            return;
        }
        if (sex != null && sex.equals("")) {
            showToast("请选择性别");
            return;
        }
        if (!Util.isMobileNO(mobile)) {
            showToast("请填写正确的手机号");
            return;
        }
        if (sfz_imga != null && sfz_imga.equals("")) {
            showToast("请上传正面身份证");
            return;
        }
        if (sfz_imgb != null && sfz_imgb.equals("")) {
            showToast("请上传反面身份证");
            return;
        }
        if (xsimg_a != null && xsimg_a.equals("")) {
            showToast("请上传正面行驶证");
            return;
        }
        if (xsimg_b != null && xsimg_b.equals("")) {
            showToast("请上传反面行驶证");
            return;
        }
        if (jsimg != null && jsimg.equals("")) {
            showToast("请上传驾驶证");
            return;
        }
        if (isbendi != null && isbendi.equals("")) {
            showToast("请设置是否为本地驾证");
            return;
        }
        if (cartype != null && cartype.equals("")) {
            showToast("请选择准驾车型");
            return;
        }

        mEngine.enroll(name, sex, mobile, user_id, sfz_imga, sfz_imgb, jsimg, xsimg_a, xsimg_b, cartype, isbendi, key).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    if (status == 200) {
                        showToast("资料已提交");
                        finish();
                    } else if (status == 106) {
                        showToast("加盟商不存在");
                    } else if (status == 201) {
                        showToast("手机号已参与过报名");
                    } else if (status == 100) {
                        showToast("请求失败");
                    } else {
                        showToast("请求异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

}
